"""FastAPI主应用."""

from contextlib import asynccontextmanager
from typing import AsyncGenerator

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles

from netsphere.api.routers import dhcp, dns, ipam, monitoring
from netsphere.config.settings import settings
from netsphere.core.database import engine
from netsphere.core.redis import close_redis
from netsphere.models.base import Base


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
    """应用生命周期管理."""
    # 启动时执行
    async with engine.begin() as conn:
        # 创建所有表
        await conn.run_sync(Base.metadata.create_all)
    
    yield
    
    # 关闭时执行
    await close_redis()


# 创建FastAPI应用
app = FastAPI(
    title="NetSphere",
    description="集中化、高可靠性、可视化的IPAM/DHCP/DNS服务管理体系",
    version=settings.app_version,
    debug=settings.debug,
    lifespan=lifespan,
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(ipam.router, prefix="/api/v1/ipam", tags=["IPAM"])
app.include_router(dhcp.router, prefix="/api/v1/dhcp", tags=["DHCP"])
app.include_router(dns.router, prefix="/api/v1/dns", tags=["DNS"])
app.include_router(monitoring.router, prefix="/api/v1/monitoring", tags=["监控"])

# 静态文件服务
app.mount("/static", StaticFiles(directory="static"), name="static")


@app.get("/")
async def root():
    """根路由."""
    return {
        "message": "Welcome to NetSphere",
        "version": settings.app_version,
        "docs": "/docs",
    }


@app.get("/health")
async def health_check():
    """健康检查."""
    return {"status": "healthy", "version": settings.app_version}